﻿/******************************************************
* author :  cwj
* email  :  chenwenji_360@live.com 
* history:  created by cwj 2015/7/25 10:08:35 
* clrversion :4.0.30319.18444
******************************************************/

using Machine.DataAccess.Common.ORM;
using Machine.DataAccess.Linq;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Machine.DataAccess.Operation.SqlServer
{
    class SqlServerDataSetOperator<TEntity> : DataSetOperatorBase<TEntity>//IDataSetOperator<TEntity>
    {
        //private static Dictionary<Type, CacheItem> keyInfos = new Dictionary<Type, CacheItem>();
        //private static readonly string sql_key = @"SELECT name from syscolumns where id = OBJECT_ID(@tableName) and colid in (select colid from sysindexkeys where id = OBJECT_ID(@tableName))";

        //private static Lazy<SqlServerDataSetOperator<TEntity>> _instance = new Lazy<SqlServerDataSetOperator<TEntity>>(() =>
        //    {
        //        return new SqlServerDataSetOperator<TEntity>();
        //    }, true);
        //public static SqlServerDataSetOperator<TEntity> Instance { get { return _instance.Value; } }
        public SqlServerDataSetOperator(ProviderElement providerElement):base(providerElement) { }
        protected override string TableBeforeChar { get { return "["; } }
        protected override string TableAfterChar { get { return "]"; } }

        //private static CacheItem GetDbKey(string tableName)
        //{
        //    using (SqlConnection con = new SqlConnection(Config.Instance.ConnectionString))
        //    {
        //        con.Open();
        //        using (var command = con.CreateCommand())
        //        {
        //            command.CommandText = sql_key;
        //            command.Parameters.Add(new SqlParameter("tableName", tableName));
        //            var keyName = command.ExecuteScalar() as string;
        //            if (keyName == null) throw new ArgumentNullException("没有这张表");
        //            return new CacheItem()
        //            {
        //                KeyName = keyName.ToLower(),
        //                TableName = tableName
        //            };
        //        }
        //    }
        //}

        //protected override CacheItem GetKeyName(Type type)
        //{
        //    if (type.Name.StartsWith("<>")) throw new NotSupportedException("不支持匿名类型的增、删、改");
        //    if (!_primaryKeyInfos.ContainsKey(type))
        //    {
        //        var tableName = type.Name;
        //        var tableAttribute = type.GetCustomAttributes(typeof(DbTableAttribute), true).FirstOrDefault() as DbTableAttribute;
        //        tableName = tableAttribute == null ? tableName : tableAttribute.TableName;
        //        _primaryKeyInfos[type] = GetDbKey(tableName);
        //    }
        //    return _primaryKeyInfos[type];
        //}

        /// <summary>
        /// 根据主键得到信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        //public TEntity GetByKey(object key)
        //{
        //    var cacheItem = GetKeyName(typeof(TEntity));
        //    string sql = string.Format("select * from {0} where {1} = @id", cacheItem.TableName, cacheItem.KeyName);
        //    List<SqlParameter> parameters = new List<SqlParameter>() { new SqlParameter(@"id", key) };
        //    return DataResult.GetResult<TEntity>(new TranslateResult(sql, parameters));
        //}

        /// <summary>
        /// 根据主键删除对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        //public bool Delete(object key)
        //{
        //    var cacheItem = GetKeyName(typeof(TEntity));
        //    var entity = GetByKey(key);
        //    if (entity == null) return false;
        //    string sql = string.Format("delete from {0} where {1} = @id", cacheItem.TableName, cacheItem.KeyName);
        //    var parameters = new List<SqlParameter>() { new SqlParameter("id", key) };
        //    return DataResult.ExecuteNonQuery(new TranslateResult(sql, parameters));
        //}

        /// <summary>
        /// 增加或更新对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        //public bool AddOrUpdate(TEntity entity)
        //{
        //    var properties = DynamicAssignment.Instance.GetDictionary(typeof(TEntity));
        //    var cacheItem = GetKeyName(typeof(TEntity));
        //    var key = properties[cacheItem.KeyName].GetValue(entity);

        //    var dbEntity = GetByKey(key);
        //    if (dbEntity == null)
        //    {
        //        return AddEntity(entity, properties, cacheItem);
        //    }
        //    else
        //    {
        //        return UpdateEntity(entity, dbEntity, properties, cacheItem);
        //    }
        //}

        //private static bool AddEntity(object entity, PropertyInvokerDic properties, CacheItem cacheItem)
        //{
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("insert into ");
        //    sql.Append(cacheItem.TableName);
        //    sql.Append("(");
        //    int columIndex = 0;
        //    foreach (var property in properties)
        //    {
        //        if (columIndex > 0) sql.Append(",");
        //        sql.Append(property.Key);
        //        columIndex++;
        //    }
        //    sql.Append(") values( ");
        //    columIndex = 0;
        //    foreach (var property in properties)
        //    {
        //        if (columIndex > 0) sql.Append(",");
        //        sql.Append(string.Format("@{0}", property.Key));
        //        columIndex++;
        //    }
        //    sql.Append(")");
        //    var parameters = new List<SqlParameter>();
        //    foreach (var property in properties)
        //    {
        //        parameters.Add(new SqlParameter(property.Key, property.Value.GetValue(entity)));
        //    }

        //    return DataResult.ExecuteNonQuery(new TranslateResult(sql.ToString(), parameters));
        //}

        //private static bool UpdateEntity(object entity, object dbEntity, PropertyInvokerDic properties, CacheItem cacheItem)
        //{
        //    StringBuilder builder = new StringBuilder();
        //    builder.Append("update ");
        //    builder.Append(cacheItem.TableName);
        //    List<SqlParameter> parameters = new List<SqlParameter>();
        //    foreach (var property in properties)
        //    {
        //        var oldValue = property.Value.GetValue(dbEntity);
        //        var newValue = property.Value.GetValue(entity);
        //        if (!oldValue.Equals(newValue))
        //        {
        //            if (parameters.Count == 0) builder.Append(" set ");
        //            else builder.Append(", ");
        //            builder.Append(string.Format("{0} = @{0} ", property.Key));
        //            parameters.Add(new SqlParameter(property.Key, newValue));
        //        }
        //    }
        //    if (parameters.Count == 0) return false;

        //    builder.Append(string.Format("where {0} = @{0}", cacheItem.KeyName));

        //    if (parameters.FirstOrDefault(x => x.ParameterName == cacheItem.KeyName) == null)
        //        parameters.Add(new SqlParameter(cacheItem.KeyName, properties[cacheItem.KeyName].GetValue(entity)));

        //    return DataResult.ExecuteNonQuery(new TranslateResult(builder.ToString(), parameters));
        //}

        //private class CacheItem
        //{
        //    public string TableName { get; set; }
        //    public string KeyName { get; set; }
        //}
    }
}
